<template>
  <div class="server-main">
    <el-form :inline="true" v-model="searchParams" class="search-form">
      <!-- 图谱平台暂时没有租户相关概念 隐藏所属租户 -->
      <!-- <el-form-item label="所属系统" class="form-input">
        <el-select
          v-model="searchParams.tenantId"
          clearable
          @change="getSourceList"
        >
          <el-option
            v-for="i in systemOptions"
            :key="i.id"
            :label="i.name"
            :value="i.id"
          ></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="数据源内外部" class="form-input">
        <el-select
          v-model="searchParams.inside"
          clearable
          @change="getSourceList"
        >
          <el-option label="外部" :value="0"></el-option>
          <el-option label="内部" :value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="数据源类型" class="form-input">
        <el-select
          v-model="searchParams.dataSourceTypeId"
          clearable
          @change="getSourceList"
        >
          <el-option
            v-for="i in sourceTypeOptions"
            :key="i.value"
            :label="i.label"
            :value="i.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="数据源名称" class="form-input">
        <el-input
          v-model.trim="searchParams.dataSourceName"
          clearable
          @clear="getSourceList"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="onSubmit(1)"
          >查询</el-button
        >
        <el-button size="small" @click="resetLoad">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="server-table">
      <div class="table-title">
        <span class="table-title-text">数据源管理</span>
        <div>
          <el-button type="primary" size="small" @click="addDataSource"
            >新增数据源</el-button
          >
        </div>
      </div>
      <el-table
        v-loading="loading"
        :data="tableList"
        :cell-style="{ color: '#333333' }"
        :header-cell-style="{ background: '#F3F4F7', color: '#000000' }"
      >
        <el-table-column
          prop="dataSourceName"
          label="数据源名称"
          width="200"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="数据源描述"
          align="center"
          width="200"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            {{ scope.row.dataSourceDescription || "---" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="dataSourceType"
          label="数据源类型"
          width="150"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="dataBaseAddress"
          label="连接地址"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="连接测试" align="center">
          <template slot-scope="scope">
            <span
              style="
                display: flex;
                align-items: center;
                justify-content: center;
              "
            >
              <img
                :src="
                  connectDict[scope.row.testConnect]
                    ? connectDict[scope.row.testConnect].icon
                    : ''
                "
                style="width: 16px; height: auto"
                alt=""
              />
              &nbsp;
              <span>{{
                connectDict[scope.row.testConnect]
                  ? connectDict[scope.row.testConnect].label
                  : "---"
              }}</span>
            </span>
          </template>
        </el-table-column>
        <!-- <el-table-column
          prop="createName"
          label="创建人"
          width="100"
          align="center"
        ></el-table-column> -->
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="150"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="dataSourceStatus"
          label="启用状态"
          width="150"
          align="center"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.dataSourceStatus"
              active-value="0"
              inactive-value="1"
              @change="changeStatus(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="250">
          <template slot-scope="scope">
            <el-link
              :underline="false"
              type="primary"
              class="ontology-edit"
              @click.native.prevent="openDetail(scope.row)"
              >详情</el-link
            >
            <el-link
              :underline="false"
              type="primary"
              class="ontology-edit"
              @click.native.prevent="openEdit(scope.row)"
              >编辑</el-link
            >
            <el-link
              :underline="false"
              type="primary"
              class="ontology-edit"
              @click.native.prevent="testConnect(scope.row)"
              >测试</el-link
            >
            <el-link
              :underline="false"
              type="primary"
              class="ontology-edit"
              @click.native.prevent="deleteRow(scope.row)"
              >删除</el-link
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        small
        layout="total, prev, pager, next, sizes, jumper"
        :page-sizes="[10, 20, 30]"
        :total="total"
        :hide-on-single-page="!total"
        :page-size.sync="searchParams.pageSize"
        :pager-count="7"
        :current-page.sync="searchParams.pageNum"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      >
      </el-pagination>
    </div>
    <OperaDialog
      ref="operaDialogRef"
      :data-source-types="sourceTypeOptions"
      @reload="getSourceList"
    />
    <DetailDialog
      ref="detailDialogRef"
      :data-source-types="sourceTypeOptions"
    />
  </div>
</template>
<script>
import { updateCookie } from "@/plugins/utils/auth";
import OperaDialog from "./components/OperaDialog.vue";
import DetailDialog from "./components/DetailDialog.vue";
export default {
  name: "DataSourceManageIndex",
  components: {
    OperaDialog,
    DetailDialog,
  },
  data: () => {
    return {
      searchParams: {
        // tenantId: null, // 所属系统
        inside: null, // 是否内部数据源
        dataSourceTypeId: null, // 数据源类型
        dataSourceName: null, // 数据源名称
        pageNum: 1, // 页码
        pageSize: 10, // 每页条数
      },
      // systemOptions: [], // 所属系统列表
      sourceTypeOptions: [], // 数据源类型
      tableList: [], // 数据列表
      total: 0, // 数据总条数
      loading: false,
      connectFlag: 2,
      connectDict: {
        0: {
          label: "失败",
          icon: require("../../../assets/svg/noSuccess.svg"),
        },
        1: { label: "成功", icon: require("../../../assets/svg/success.svg") },
        2: {
          label: "无",
          icon: require("../../../assets/svg/waitFillBlue.svg"),
        },
      },
    };
  },
  computed: {},
  created() {
    if (this.$route.query.token) {
      updateCookie("token", this.$route.query.token);
    }
    // 获取所属系统列表
    // this.getSubSysOptions();
    // 获取数据源类型
    this.getSourceTypeOptions();
    // 获取数据列表
    this.getSourceList();
  },
  methods: {
    // 获取搜索条件选项
    // getSubSysOptions() {
    //   this.$axios
    //     .post(this.$api.dataConnection.dataSource.getSubSystemList)
    //     .then((res) => {
    //       this.systemOptions = res.data.data;
    //     });
    // },
    getSourceTypeOptions() {
      this.$axios
        .post(this.$api.dataConnection.dataSource.getSourceTypeList)
        .then((res) => {
          this.sourceTypeOptions = res.data.data;
        });
    },
    // 获取事件查询列表
    getSourceList() {
      this.loading = true;
      this.$axios
        .post(
          this.$api.dataConnection.dataSource.getDataSourceList,
          this.searchParams
        )
        .then((res) => {
          let data = res.data.data;
          this.tableList = data.list;
          this.total = data.totalCount;
          this.searchParams.pageSize = data.pageSize;
          this.searchParams.pageNum = data.pageNum;
          this.$utils.backtop(this.containerDom);
        })
        .catch((err) => {
          console.error(err);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 查询
    onSubmit(pageNum) {
      this.searchParams.pageNum = pageNum ? pageNum : this.searchParams.pageNum;
      this.getSourceList();
    },
    resetLoad() {
      this.searchParams.pageNum = 1;
      // this.searchParams.tenantId = null;
      this.searchParams.inside = null;
      this.searchParams.dataSourceTypeId = null;
      this.searchParams.dataSourceName = null;
      this.getSourceList();
    },
    // 修改当前页码
    handleCurrentChange() {
      this.getSourceList();
    },
    // 修改每页条数
    handleSizeChange() {
      this.getSourceList();
    },
    // 新增数据源
    addDataSource() {
      this.$refs.operaDialogRef.openDialog("新增数据源");
    },
    // 修改状态
    changeStatus(row) {
      this.$confirm(
        `是否确认${row.dataSourceStatus === "0" ? "启用" : "禁用"}该数据源？`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          const params = {
            status: row.dataSourceStatus,
            id: row.dataSourceId,
          };
          this.$axios
            .post(this.$api.dataConnection.dataSource.enableDataSource, params)
            .finally(() => {
              this.getSourceList();
            });
        })
        .catch(() => {
          this.$message.info("已取消");
          row.dataSourceStatus = row.dataSourceStatus === "0" ? "1" : "0";
        });
    },
    // 详情
    openDetail(row) {
      this.$axios
        .get(this.$api.dataConnection.dataSource.getDataSourceInfo, {
          params: {
            id: row.dataSourceId,
          },
        })
        .then((res) => {
          if (res.data.code === 200) {
            this.$refs.detailDialogRef.openDialog(res.data.data);
          } else {
            this.$message.error(res.data.message);
          }
        })
        .catch((err) => this.$message.error(err));
    },
    openEdit(row) {
      this.$axios
        .get(this.$api.dataConnection.dataSource.getDataSourceInfo, {
          params: {
            id: row.dataSourceId,
          },
        })
        .then((res) => {
          if (res.data.code === 200) {
            this.$refs.operaDialogRef.openDialog("编辑数据源", res.data.data);
          } else {
            this.$message.error(res.data.message);
          }
        })
        .catch((err) => this.$message.error(err));
    },
    // 测试连接
    testConnect(row) {
      this.$axios
        .get(this.$api.dataConnection.dataSource.getDataSourceInfo, {
          params: {
            id: row.dataSourceId,
          },
        })
        .then((res) => {
          if (res.data.code === 200) {
            const params = res.data.data;
            const sourceType = this.sourceTypeOptions.find(
              (ele) => ele.value === params.dataSourceTypeId
            );
            const sourceTypeName = sourceType ? sourceType.label : "";
            params.dataBaseAddress = `${
              params.access ? params.access + ":" : ""
            }${sourceTypeName}://${params.dataSourceIp || ""}:${
              params.dataSourcePort || ""
            }/${params.dataBaseName || ""}${
              params.extra ? "?" + params.extra : ""
            }`;
            this.$axios
              .post(this.$api.dataConnection.dataSource.testConnection, params)
              .then((resp) => {
                const { code, message, data } = resp.data;
                if (code === 200) {
                  this.connectFlag = 1;
                  if (data === "success") {
                    this.$notify.success({
                      title: "连接成功",
                      message: "数据源连接测试通过， 请保存",
                      showClose: false,
                    });
                    if (row.testConnect !== 1) {
                      this.submitEditRow({...res.data.data, testConnect: 1}).then(() => {
                        this.$set(row, 'testConnect', 1)
                      })
                    }
                  } else {
                    this.$notify.error({
                      title: "连接未成功",
                      message: "数据源连接测试未通过，请检查设置信息",
                      showClose: false,
                    });
                    if (row.testConnect !== 0) {
                      this.submitEditRow({...res.data.data, testConnect: 0}).then(() => {
                        this.$set(row, 'testConnect', 0)
                      })
                    }
                  }
                } else if (code === 8008) {
                  this.connectFlag = 0;
                  this.$message.error(message);
                  if (row.testConnect !== 0) {
                    this.submitEditRow({...res.data.data, testConnect: 0}).then(() => {
                      this.$set(row, 'testConnect', 0)
                    })
                  }
                }
              })
              .catch(() => {})
          } else {
            this.$message.error(res.data.message);
          }
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
    // 删除数据
    deleteRow(row) {
      this.$confirm(`确定删除此数据源？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let params = { id: row.dataSourceId };
        this.$axios
          .get(this.$api.dataConnection.dataSource.deleteDataSource, {
            params,
          })
          .then(() => {
            this.$message.success("删除成功！");
            this.getSourceList();
          });
      });
    },
    // 更新数据 用于测试连接状态后修改数据
    submitEditRow(row) {
       return this.$axios.post(this.$api.dataConnection.dataSource.editDataSource, row)
    }
  },
};
</script>
<style lang="scss" scoped>
.server-main {
  position: relative;

  .search-form {
    padding: 16px 32px;
    border-radius: 4px;
    background: #ffffff;

    .el-form-item {
      margin-bottom: 0;
    }

    .form-input {
      margin-right: 32px;

      /deep/ .el-input__inner {
        width: 240px;
        height: 32px;
        background: #ffffff;
        border-radius: 2px;
        border: 1px solid #e0e0e0;
      }
    }
  }

  .el-select {
    /deep/ .el-input__inner {
      width: 240px;
      height: 32px;
      background: #ffffff;
      border-radius: 2px;
      border: 1px solid #e0e0e0;
    }
  }

  .server-table {
    margin-top: 16px;
    padding: 16px 32px 64px;
    border-radius: 4px;
    background: #ffffff;

    .table-title {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .table-title-text {
        border-left: 5px solid $--color-primary;
        padding-left: 10px;
        margin: 8px 0;
        font-size: 16px;
        line-height: 16px;
      }

      margin-bottom: 10px;
    }

    .little-circle-blue {
      display: inline-block;
      width: 6px;
      height: 6px;
      border-radius: 3px;
      background: #55c898;
      position: relative;
      right: 4px;
      top: -2px;
    }

    .little-circle-red {
      display: inline-block;
      width: 6px;
      height: 6px;
      border-radius: 3px;
      background: #ee5564;
      position: relative;
      right: 6px;
      top: -2px;
    }

    .page-wrapper {
      margin-top: 28px;
      display: flex;
      justify-content: flex-end;
      color: rgba(0, 0, 0, 0.65);

      .data-counter {
        font-weight: 400;
        line-height: 32px;
        margin-right: 24px;
      }

      /deep/ .btn-prev,
      /deep/ .btn-next {
        margin: 0 4px;
        min-width: 28px;
        border-radius: 2px;
        border: 1px solid rgba(0, 0, 0, 0.15);
        padding: 0;
      }

      /deep/ .el-pager .number {
        min-width: 28px;
        height: 28px;
        border-radius: 2px;
        border: 1px solid rgba(0, 0, 0, 0.15);
        margin: 0 4px;
        cursor: pointer;
      }
    }
  }

  .ontology-edit {
    padding: 0 10px;

    & + .ontology-edit {
      border-left: 1px solid #dddddd;
    }
  }

  /deep/ .el-table__append-wrapper {
    padding: 10px;
  }

  .el-pagination {
    float: right;
    margin-top: 20px;

    .form-input /deep/ .el-input {
      width: 200px;
    }

    /deep/ .el-input__inner {
      height: 22px;
    }
  }

  /deep/ .el-dialog {
    border-radius: 5px;
  }
}
</style>
